import 'dart:convert';

import 'package:mmkv_flutter/mmkv_flutter.dart';

class LocalStorage {
  static LocalStorage get instance => _instance;
  static LocalStorage _instance;

  static Future<void> initialize() async {
    // nothing
    LocalStorage._instance =
        LocalStorage(mmkv: await MmkvFlutter.getInstance());
  }

  MmkvFlutter mmkv;

  LocalStorage({this.mmkv});

  Future<int> getInt(String key) {
    return this.mmkv.getInt(key);
  }

  Future<double> getDouble(String key) {
    return this.mmkv.getDouble(key);
  }

  Future<bool> getBool(String key) {
    return this.mmkv.getBool(key);
  }

  Future<String> getString(String key) {
    return this.mmkv.getString(key);
  }

  Future<bool> clear() {
    return this.mmkv.clear();
  }

  Future<bool> removeByKey(String key) {
    return this.mmkv.removeByKey(key);
  }

  Future<bool> setBool(String key, bool value) {
    return this.mmkv.setBool(key, value);
  }

  Future<bool> setInt(String key, int value) {
    return this.mmkv.setInt(key, value);
  }

  Future<bool> setDouble(String key, double value) {
    return this.mmkv.setDouble(key, value);
  }

  Future<bool> setString(String key, String value) {
    return this.mmkv.setString(key, value);
  }

  Future<bool> setJsonObject(String key, dynamic value) {
    return this.mmkv.setString(key, jsonEncode(value));
  }

  Future<dynamic> getJsonObject(String key) {
    return this.mmkv.getString(key).then((String val) {
      if (val != null) {
        return jsonDecode(val);
      } else {
        return null;
      }
    });
  }
}
